<?php
/**
 * Created by PhpStorm.
 * User: geyouwen
 * Date: 16/7/3
 * Time: 下午6:17
 */
namespace Backend\Model;

use Think\Exception;
use Think\Model;

class AdminModel extends Model
{
    protected $connection = 'DB_CONFIG1';

    protected $table      = 'admin';

    protected $prefix     = 'tp_';


    //用户身份验证
    public function checkLogin($name, $password)
    {
        $where = array(
            'username' => $name,
            'password' => md5(C('APP_MCRYPT').$password),
        );
        $data  = $this->where($where)->find();
        return $data;
    }

    //更新登录时间 登录次数
    public function updateLogin($user_id)
    {
        try{
            //登录次数 +1
            $this->where(array('userid' => $user_id))->setInc('loginnum',1);
            //更新登录时间
            $update = array(
                'lastdate' => time(),
                'lastip'   => get_client_ip(),
            );
            $this->where(array('userid' => $user_id))->save($update);
        } catch(Exception $e)
        {
            return false;
        }
        return true;
    }

    //验证同一个IP的登录次数
    public function checkloginnums()
    {
        $ip = get_client_ip();
        $num = intval(S('login_'.$ip));
        S('login_'.$ip, $num+1, array('type'=>'file','expire'=>C('login_over_times')*60));
        if($num >= C('login_over_num'))
        {
          return $msg = array('status' => 0, 'msg' => '请勿频繁登录，'.C('login_over_times').'分钟后再尝试');
        }
        return false;

    }

    //检测字段是否有重复
    public function is_exist($check_field, $check_value, $userid)
    {
        $where = array(
            $check_field => $check_value
        );
        if($userid)
        {
            array_push($where, array('userid' => array('neq', $userid)));
        }
        return $this->where($where)->field('userid,mobile,email,username')->select();
    }

}